package com.javatest.springboot3minio.dao;

import com.javatest.springboot3minio.entity.AttachmentInfo;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

/**
 * Created with IntelliJ IDEA. Description:
 *
 * @author lzy
 * @since 2024-01-12 下午1:16
 */
@Repository
public class AttachmentManageDaoImpl implements AttachmentManageDao {
  private JdbcTemplate jdbcTemplate;
  private JdbcClient jdbcClient;

  @Autowired
  public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  @Autowired
  public void setJdbcClient(JdbcClient jdbcClient) {
    this.jdbcClient = jdbcClient;
  }

  /**
   * Add new attachment int.
   *
   * @param attachment 附件
   * @return int
   */
  @Override
  public int addNewAttachment(AttachmentInfo attachment) {
    // 配置一个获取插入序列号的对象
    KeyHolder keyHolder = new GeneratedKeyHolder();
    final String sql =
        "insert into DM_ATTACHMENT_INFO(C_ATTACHMENT_NAME, E_ATTACHMENT_TYPE, C_PROJECT_ID) values(?,?,?)";
    PreparedStatementCreator preparedStatementCreator =
        con -> {
          PreparedStatement ps = con.prepareStatement(sql, new String[] {"I_ID"});
          List<Object> params = getParamsForAttachmentInfo(attachment);
          int index = 1;
          for (Object param : params) {
            ps.setObject(index, param);
            index++;
          }
          return ps;
        };
    // 插入成功,返回数据库自增序列号
    if (jdbcTemplate.update(preparedStatementCreator, keyHolder) > 0) {
      return Objects.requireNonNull(keyHolder.getKey()).intValue();
    }
    // 插入失败返回-1
    return -1;
  }

  @Override
  public int countAttachment(AttachmentInfo attachment) {

    final String sql =
        "select count(i_id) from DM_ATTACHMENT_INFO where c_attachment_name=? and e_attachment_type=? and c_project_id=?";
    return jdbcClient
        .sql(sql)
        .param(attachment.getAttachmentName())
        .param(attachment.getAttachmentType())
        .param(attachment.getProjectId())
        .query(Integer.class)
        .single();
  }

  /**
   * Gets attachment list.
   *
   * @param projectId the project id
   * @param attachmentType the attachment type
   * @return attachment list
   */
  @Override
  public List<AttachmentInfo> getAttachmentList(String projectId, String attachmentType) {
    String sql =
        "select i_id as id, c_attachment_name as attachmentName, e_attachment_type as attachmentType, c_project_id as projectId from DM_ATTACHMENT_INFO";
    final Map<String, Object> paramMap = getParams(projectId, attachmentType);
    Object[] params = new Object[0];
    if (!paramMap.isEmpty()) {
      sql += " where " + String.join(" and ", paramMap.keySet());
      params = paramMap.values().toArray();
    }

    return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(AttachmentInfo.class), params);
  }

  /**
   * Del attachment int.
   *
   * @param id the id
   * @return int
   */
  @Override
  public int delAttachment(int id) {
    final String sql = "delete from DM_ATTACHMENT_INFO where I_ID = ?";
    return jdbcClient.sql(sql).param(id).update();
  }

  /**
   * Gets params for attachment info.
   *
   * @param info the info
   * @return the params for attachment info
   */
  private static List<Object> getParamsForAttachmentInfo(AttachmentInfo info) {
    return List.of(info.getAttachmentName(), info.getAttachmentType(), info.getProjectId());
  }

  /**
   * Gets params.
   *
   * @param projectId the project id
   * @param attachmentType the attachment type
   * @return the params
   */
  private static Map<String, Object> getParams(String projectId, String attachmentType) {
    final Map<String, Object> paramMap = new HashMap<>();
    if (StringUtils.isNoneBlank(projectId)) {
      paramMap.put("C_PROJECT_ID=?", projectId);
    }
    if (StringUtils.isNoneBlank(attachmentType)) {
      paramMap.put("E_ATTACHMENT_TYPE=?", attachmentType);
    }
    return paramMap;
  }
}
